package com.lry.crawlers.fiction.processor;


import com.lry.crawlers.fiction.entity.FictionVariable;
import com.lry.crawlers.fiction.service.FictionService;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FictionProcessor implements PageProcessor {

    public FictionVariable fictionVariable;

    public FictionService fictionService;

    public FictionProcessor(){
    }

    public FictionProcessor(FictionVariable fictionVariable,FictionService fictionService){
        this.fictionVariable = fictionVariable;
        this.fictionService = fictionService;
    }



    private Site site = Site.me()
            .setSleepTime(1)//采集间隔时间
            .setTimeOut(1000*10)//超时时间
            .setRetrySleepTime(3000)//重试时间
            .setRetryTimes(3);//重试次数

    public Site getSite() {
        return site;
    }
    

    //解析页面
    public void process(Page page) {

        String url = page.getUrl().toString();
        String[] fictiontitlelss = fictionVariable.getFictionTitle().split("-!-");
        List<String> fictiontitlee = page.getHtml().xpath(fictiontitlelss[0]).regex(fictiontitlelss.length !=1 ? fictiontitlelss[1] : ".+").all();
        String[] titless = fictionVariable.getTitle().split("-!-");
        List<String> titlee = page.getHtml().xpath(titless[0]).regex(titless.length !=1 ? titless[1] : ".+").all();
        String[] contentss = fictionVariable.getContent().split("-!-");
        List<String> contentt = page.getHtml().xpath(contentss[0]).regex(contentss.length !=1 ? contentss[1] : ".+").all();
        //小说搜索
        if(fictiontitlee.size()!=0){
            List<String> title = new ArrayList<String>();
            try {
                //获取小说信息：title，desc,author,fictionType,cover,FictionUrl,FictionId
                String[] titles = fictionVariable.getFictionTitle().split("-!-");
                title = page.getHtml().xpath(titles[0]).regex(titles.length != 1 ? titles[1] : ".+").all();
            }catch (Exception e){}

            //通过小说标签判断搜索内容是否存在
            if(title.size()!=0){
                String[] fictionUrls = fictionVariable.getFictionUrl().split("-!-");
                String[] pageUrls = fictionVariable.getPage().split("-!-");
                List<String> fictionUrl = page.getHtml().xpath(fictionUrls[0]).regex(fictionUrls.length !=1 ? fictionUrls[1] : ".+").all();
                String pageUrl = page.getHtml().xpath(pageUrls[0]).regex(pageUrls.length !=1 ? pageUrls[1] : ".+").get();
                //获取小说章节与内容的对应的chapterId,并处理无域名url
                if(!fictionUrl.get(0).contains("http")){
                    List<String> fictionUrll = new ArrayList<>();
                    fictionUrl.forEach(str -> {
                        fictionUrll.add(fictionVariable.getProtocol()+"://"+fictionVariable.getUrl()+str);
                    });
                    fictionUrl = fictionUrll;
                }
                List<Integer> duplicates = fictionService.removeDuplicates(title);
                for (int i : duplicates) {
                    fictionUrl.set(i,null);
                }
                while (fictionUrl.remove(null));


                if (fictionUrl.size() != 0) {
                    //把小说链接加入爬取列表
                    page.addTargetRequests(fictionUrl);
                }
                //把小说下一页加入爬取列表
                if (pageUrl != null) {
                    if (pageUrl.contains("http")) {
                    } else if(pageUrl.contains("/")){
                        pageUrl = fictionVariable.getProtocol() + "://" + fictionVariable.getUrl() + pageUrl;
                    }else if(!pageUrl.contains("javascript")){
                        pageUrl = url + pageUrl;
                    }
                    page.addTargetRequest(pageUrl);
                }
            }
        }
        //小说章节
        else if (titlee.size()!=0){
            //获取小说章节信息：chapterTitle，chapterUrl，chapterId
            //获取小说信息：title，desc,author,fictionType,cover,FictionUrl,FictionId
            String[] titles = fictionVariable.getTitle().split("-!-");
            String[] descs = fictionVariable.getDescs().split("-!-");
            String[] authors = fictionVariable.getAuthor().split("-!-");
            String[] fictionTypes = fictionVariable.getFictionType().split("-!-");
            String[] covers = fictionVariable.getCover().split("-!-");
            String[] chapterTitles = fictionVariable.getChapterTitle().split("-!-");
            String[] chapterUrls = fictionVariable.getChapterUrl().split("-!-");
            String[] updateTimes = fictionVariable.getUpdateTime().split("-!-");
            List<String> title = page.getHtml().xpath(titles[0]).regex(titles.length !=1 ? titles[1] : ".+").all();
            List<String> desc = page.getHtml().xpath(descs[0]).regex(descs.length !=1 ? descs[1] : ".+").all();
            List<String> author = page.getHtml().xpath(authors[0]).regex(authors.length !=1 ? authors[1] : ".+").all();
            List<String> fictionType = page.getHtml().xpath(fictionTypes[0]).regex(fictionTypes.length !=1 ? fictionTypes[1] : ".+").all();
            List<String> cover = page.getHtml().xpath(covers[0]).regex(covers.length !=1 ? covers[1] : ".+").all();
            List<String> chapterTitle = page.getHtml().xpath(chapterTitles[0]).regex(chapterTitles.length !=1 ? chapterTitles[1] : ".+").all();
            List<String> chapterUrl = page.getHtml().xpath(chapterUrls[0]).regex(chapterUrls.length !=1 ? chapterUrls[1] : ".+").all();
            List<String> updateTime = page.getHtml().xpath(updateTimes[0]).regex(updateTimes.length !=1 ? updateTimes[1] : ".+").all();
            if(chapterTitles.length ==3){
                String[] splitTitl = chapterTitles[2].split(",");
                if(splitTitl.length ==1){
                    chapterTitle = chapterTitle.subList(Integer.parseInt(splitTitl[0]),chapterTitle.size());
                }else{
                    chapterTitle = chapterTitle.subList(Integer.parseInt(splitTitl[0]),Integer.parseInt(splitTitl[1]));

                }
            }
            if(chapterUrls.length == 3){
                String[] splitUrls = chapterUrls[2].split(",");
                if(splitUrls.length ==1){
                    chapterUrl = chapterUrl.subList(Integer.parseInt(splitUrls[0]),chapterUrl.size());
                }else{
                    chapterUrl = chapterUrl.subList(Integer.parseInt(splitUrls[0]),Integer.parseInt(splitUrls[1]));
                }

            }

            //判断是否存在
            if (title.size() == 0) {
                title.add(" ");
            }
            if (author.size() == 0) {
                author.add(" ");
            }
            if (fictionType.size() == 0) {
                fictionType.add(" ");
            }
            if (cover.size() == 0) {
                cover.add(" ");
            }
            if (updateTime.size() == 0) {
                updateTime.add(" ");
            }
            if (desc.size() == 0) {
                desc.add(" ");
            }
            if (chapterTitle.size() == 0) {
                chapterTitle.add(" ");
            }
            if (chapterUrl.size() == 0) {
                chapterUrl.add(" ");
            }
            boolean duplicate = fictionService.removeDuplicate(title.get(0));
            if(!duplicate) {
                List<String> chapterId = new ArrayList<String>();
                //获取对应的fictionId
                String[] chapterUrl1 = chapterUrl.get(0).split("/");
                String fictionId = chapterUrl1[chapterUrl1.length - 2].replace(".html", "");
                //获取小说章节与内容的对应的chapterId,并处理无域名url
                if (!chapterUrl.get(0).contains("http")) {
                    ArrayList<String> listUrl = new ArrayList<String>();
                    chapterUrl.forEach(str -> {
                        listUrl.add(fictionVariable.getProtocol() + "://" + fictionVariable.getUrl() + str);
                        String[] st = str.split("/");
                        chapterId.add(st[st.length - 1].replace(".html", ""));
                    });
                    chapterUrl = listUrl;
                } else {
                    chapterUrl.forEach(u -> {
                        String[] st = u.split("/");
                        chapterId.add(st[st.length - 1].replace(".html", ""));
                    });
                }
                if(!cover.get(0).contains("http")){
                    cover.set(0,fictionVariable.getProtocol() + "://" + fictionVariable.getUrl() + cover.get(0));
                }
                //创建储存Map数据，用于业务处理
                Map<String, Object> chapterMap = new HashMap<>();
                chapterMap.put("key", "fictionChapter");
                chapterMap.put("title", title.get(0));
                chapterMap.put("desc", desc.get(0));
                chapterMap.put("author", author.get(0));
                chapterMap.put("updateTime", updateTime.get(0));
                chapterMap.put("fictionType", fictionType.get(0));
                chapterMap.put("cover", cover.get(0));
                chapterMap.put("chapterTitle", chapterTitle);
                chapterMap.put("chapterId", chapterId);
                chapterMap.put("fictionId", fictionId);
                chapterMap.put("updateUrl", url);
                chapterMap.put("id", fictionVariable.getId());
                //提交数据，给Pipeline处理
                page.putField("data", chapterMap);
                //把小说章节链接加入爬取列表
                page.addTargetRequests(chapterUrl);
            }

        }
        //小说内容
        else if(contentt.size()!=0){
            //获取小说内容信息：content
            String[] contents = fictionVariable.getContent().split("-!-");
            List<String> content = page.getHtml().xpath(contents[0]).regex(contents.length !=1 ? contents[1] : ".+").all();
            //获取小说内容与章节对应的fictionId
            String[] listUrl =  page.getUrl().toString().split("/");
            String chapterId = listUrl[listUrl.length-1].replace(".html","");
            String fictionId = listUrl[listUrl.length-2].replace(".html","");
            //创建储存Map数据，用于业务处理
            Map<String,Object> map = new HashMap<>();
            map.put("key","content");
            map.put("content",content);
            map.put("chapterId",chapterId);
            map.put("fictionId",fictionId);
            map.put("id",fictionVariable.getId());
            map.put("fictionVariable",fictionVariable);
            //提交数据，给Pipeline处理
            page.putField("data",map);
            //小说章节
            }
        }

    }

